package org.budo.dubbo.protocol.async.repository.aliyun.mns;

import java.util.List;

import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.aliyun.mns.client.CloudQueue;
import com.aliyun.mns.model.Message;

import lombok.Getter;
import lombok.Setter;

/**
 * @author lmw
 */
@Getter
@Setter
public abstract class AbstractListMessageAsyncCallback extends AbstractAsyncCallback<List<Message>> {
    private static final Logger log = LoggerFactory.getLogger(AbstractListMessageAsyncCallback.class);

    private CloudQueue cloudQueue;

    @Override
    public void onSuccess(List<Message> messages) {
        this.processMessageList(messages);
    }

    private void processMessageList(List<Message> messages) {
        if (null == messages || messages.isEmpty()) {
            log.info("#25 onSuccess, messages=" + messages + ", return, this=" + this);
            return;
        }

        for (Message message : messages) {
            if (null == message || null == message.getMessageBodyAsBytes()) {
                log.error("#28 null message, message=" + message + ", this=" + this);
                continue;
            }

            Object result = null;
            try {
                result = this.processMessage(message);
            } catch (Throwable e) {
                log.error("#38 processMessage error, e=" + e, e);
            }

            // 执行本地方法后，删除消息，即使执行报错
            // TODO 这样好么
            this.getCloudQueue().asyncDeleteMessage(message.getReceiptHandle(), new DeleteCallback()); // 处理后删除消息

            if (log.isDebugEnabled()) {
                log.debug("#67 messageId=" + message.getMessageId() + ", requestId=" + message.getRequestId() + ", result=" + result + ", this=" + this);
            }
        }
    }

    /**
     * 处理单条消息
     */
    protected abstract Object processMessage(Message message) throws Throwable;

    @Override
    public String toString() {
        return super.toString() + ", cloudQueue=" + this.getCloudQueue();
    }
}